﻿using Blog.Application.Condition;
using Blog.Application.DTO;
using Blog.Application.Service;
using Blog.Domain;
using Core.Cache;
using Core.Common;
using Core.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace BlogWebApi.Controllers
{
    [Route("api/user")]
    [ApiController]
    public class UserController: ControllerBase
    {
        private ITidingsService _tidingsService;
        private IUserService _userService;
        public UserController(ITidingsService tidingsService, IUserService userService)
        {
            _tidingsService = tidingsService;
            _userService = userService;
        }
        [Route("loginuser")]
        [HttpGet]
        public ApiResult GetUser()
        {
            UserDTO userDTO = Auth.GetLoginUser();
            TidingsCondition tidingsCondition = new TidingsCondition();
            tidingsCondition.Account = userDTO.Account;
            tidingsCondition.IsRead = false;
            int count = _tidingsService.SelectCount(tidingsCondition); 
            return ApiResult.Success(new { photo = userDTO.HeadPhoto, count = count, account = userDTO.Account });
        }
        [Route("token")]
        [HttpGet]
        public ApiResult  GetUserByToken()
        {
            UserDTO userDTO= Auth.GetLoginUser();          
            return ApiResult.Success(userDTO);
        }
        [Route("{account}")]
        [HttpGet]
        public ApiResult GetUserByAccount(string account)
        {
            UserCondition condition = new UserCondition();
            condition.Account = account;
            UserDTO userDTO = _userService.SelectSingle(condition);
            return ApiResult.Success(userDTO);
        }   
        [HttpPost("update")]
        public ApiResult Update([FromBody]UserDTO userDTO)
        {
            UserDTO loginUser = Auth.GetLoginUser();
            if (loginUser.LoginType == LoginType.QQ)
                throw new ValidationException("QQ登录的用户无法修改");
            _userService.Update(userDTO);
            Request.Headers.TryGetValue("loginToken", out StringValues oldToken);
            userDTO.LoginType = loginUser.LoginType;
            userDTO.HeadPhoto = loginUser.HeadPhoto;
            string token = Auth.CreateToken(userDTO, oldToken);
            return ApiResult.Success(token);
        }
    }
}
